/***********************************************
 @Name :        小谭老师
 @Time :        2025-2-22
 @Email :       tan.zhipeng@outlook.com
 @Comment :     功能窗口 智能对话
 @FileName :    widget_funca_smart_chat.cpp
 @Version :     1.0
************************************************/

#include "widget_funca_smart_chat.h"
#include "ui_widget_funca_smart_chat.h"
#include <QDebug>
#include <QTimer>
#include <QScrollBar>

Widget_funcA_Smart_chat::Widget_funcA_Smart_chat(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget_funcA_Smart_chat)
{
    ui->setupUi(this);
    manager = new QNetworkAccessManager(this);
    // 设定按钮大小
    ui->Button_send->setFixedSize(80 , 30);
    ui->Button_send->setAlignment(Qt::AlignCenter);
    ui->Button_send->setText("发送");
    // 背景色、边框、圆角
    ui->Button_send->setStyleSheet(R"(
            QLabel {
            font-family:"楷体";
            font-size:24px;
            background-color: #0099ff;
            border: 1px solid #0099ff;
            border-radius: 8px;
            color:#ffffff;
            }
            QLabel:hover {
                background-color: #66c2ff;
            }
    )");
    // 加载gif动图
    loadingMovie = new QMovie(":/加载动图");
    loadingMovie->setScaledSize(QSize(28, 28));  // 设置 GIF 显示大小
    
    // 设置透明背景并去除边框
    ui->textEdit->setStyleSheet("background: transparent; border: none;");
    // 确保文本框能够正常输入
    ui->textEdit->setAttribute(Qt::WA_OpaquePaintEvent, false);
    // 设置字体
    ui->textEdit->setFont(QFont("楷体" , 13));
    
    QVBoxLayout *vlayout=new QVBoxLayout(ui->widget_show);
    scrollArea=new QScrollArea(ui->widget_show);
    scrollArea->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    scrollArea->setWidgetResizable(true);
    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);  // 禁用水平滚动条
    vlayout->addWidget(scrollArea);
    // 创建内容区域和布局
    contentWidget = new QWidget();
    contentLayout = new QVBoxLayout(contentWidget);
    contentWidget->setStyleSheet("background-color:#ccebff;border:1px solid #ccebff;");
    contentLayout->setAlignment(Qt::AlignTop);  // 消息从顶部开始排列
    contentLayout->setSpacing(10);  // 消息之间的间距
    contentLayout->setContentsMargins(0, 0, 0, 0); // 移除布局边距
    contentWidget->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Expanding);
    // 将内容区域设置到滚动区域中
    scrollArea->setWidget(contentWidget);
    
    // 上右下左 #f2f2f2
    scrollArea->setStyleSheet(
        "QScrollArea{"
        "background: transparent; border: none;"
        "}"
        // 简约垂直滚动条
        "QScrollBar:vertical {"
        "   border: none;"
        "   background: #f0f2f5;"
        "   width: 6px;"
        "   margin: 0px 0px 0px 0px;"
        "   border-radius: 3px;"
        "}"
        
        "QScrollBar::handle:vertical {"
        "   background: #c2c7d0;"
        "   border-radius: 3px;"
        "   min-height: 30px;"
        "}"
        
        "QScrollBar::handle:vertical:hover {"
        "   background: #a8aeb8;"
        "}"
        
        "QScrollBar::add-line:vertical, QScrollBar::sub-line:vertical {"
        "   height: 0px;"
        "   background: none;"
        "}"
        
        "QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {"
        "   background: none;"
        "}"
        
        );
    
    // 连接发射信号和槽函数
    connect(ui->Button_send , &Button_Cust_Base::signals_click , this , &Widget_funcA_Smart_chat::Slota_Add_Send_Message);
    connect(manager, &QNetworkAccessManager::finished, this, &Widget_funcA_Smart_chat::handleNetworkReply);
}

Widget_funcA_Smart_chat::~Widget_funcA_Smart_chat()
{
    delete ui;
    delete loadingMovie;
    delete manager;
}

void Widget_funcA_Smart_chat::Slota_Add_Send_Message()
{
    if(!ui->textEdit->toPlainText().isEmpty())
    {
        QString text=ui->textEdit->toPlainText();
        // 清空输入框文本
        ui->textEdit->clear();
        // 创建一个消息对象
        ChatBox *msgWidget=new ChatBox(QPixmap(":/头像"),"我",contentWidget,true);
        msgWidget->setChatMassage(text);
        // 添加到主布局
        contentLayout->addWidget(msgWidget);
        
        // 发送请求
        // 构建请求JSON
        QJsonObject requestObj;
        requestObj["model"] = "deepseek-r1:1.5b";
        requestObj["prompt"] = text;
        requestObj["stream"] = false;
        QString url = QString("http://localhost:11434/api/generate");
        QNetworkRequest request(url);
        // 设置请求头
        request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
        manager->post(request,QJsonDocument(requestObj).toJson());
        // 自动滚动到底部 延时50ms后执行 定时器主要为了延时50ms
        QTimer::singleShot(50, [this]() {
            QScrollBar* bar = scrollArea->verticalScrollBar();
            bar->setValue(bar->maximum());
        });
        
        // 加载GIF动画 禁用发送按钮 
        ui->Button_send->setText("");
        ui->Button_send->setEnabled(false);
        ui->Button_send->setMovie(loadingMovie);
        loadingMovie->start();
        // 发送请求时切换为加载样式
        ui->Button_send->setStyleSheet("background-color: transparent;");  // 透明背景（显示GIF时用）
    }
    
}

void Widget_funcA_Smart_chat::handleNetworkReply(QNetworkReply *reply)
{
    // 响应处理
    // response done_reason
    if (reply->error() != QNetworkReply::NoError) {
        qDebug()<< "请求失败!";
        reply->deleteLater();
        return;
    }
    QByteArray replyByteArray=reply->readAll();
    QJsonDocument document=QJsonDocument::fromJson(replyByteArray);
    QJsonObject jsonObj=document.object();
    QString responseText=jsonObj["response"].toString();
    // qDebug()<<responseText;
    // 对特殊字符进行处理
    if(responseText.contains("<think>")){
        responseText.replace("<think>","思考中...");
    }
    if(responseText.contains("</think>")){
        responseText.replace("</think>","==========思考结束==========");
    }
    // 创建一个消息对象
    ChatBox *msgWidget=new ChatBox(QPixmap(":/青柠AI"),"deepSeek",contentWidget,false);
    msgWidget->setChatMassage(responseText);
    // 添加到主布局
    contentLayout->addWidget(msgWidget);
    // 自动滚动到底部 延时50ms后执行 定时器主要为了延时50ms
    QTimer::singleShot(300, [this]() {
        QScrollBar* bar = scrollArea->verticalScrollBar();
        bar->setValue(bar->maximum());
    });
    
    ui->Button_send->setEnabled(true);
    loadingMovie->stop();
    ui->Button_send->setMovie(nullptr);
    ui->Button_send->setText("发送");
    // 重新加载样式
    ui->Button_send->setStyleSheet(R"(
            QLabel {
            font-family:"楷体";
            font-size:24px;
            background-color: #0099ff;
            border: 1px solid #0099ff;
            border-radius: 8px;
            color:#ffffff;
            }
            QLabel:hover {
                background-color: #66c2ff;
            }
    )");
    reply->deleteLater();
}












